// import { useUserStore } from "@/stores/userInfo";
import { useUserStore } from "@/stores/userInfo";
import axios, { type AxiosInstance, type AxiosResponse } from "axios";

const axiosInstance: AxiosInstance = axios.create({
  baseURL: window.config.baseUrl, // 修改为你的后端服务地址
  timeout: 10000, // 请求超时时间
});

axiosInstance.interceptors.request.use(
  (config) => {
    const store = useUserStore();
    // // 可以在这里添加认证token等通用请求头
    config.headers.Authorization = `Bearer ${store.token}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (response: AxiosResponse<any>) => response, // 确保从响应中直接返回data部分
  (error) => {
    if (error.response && error.response.status === 401) {
      const store = useUserStore();
      store.$reset();
      window.location.href = "/login";
    }
    console.error("API call error:", error.message);
    return Promise.reject(error);
  }
);
export default axiosInstance;
